define([
	"UtilDir/util",
	"UtilDir/tool",
	"UtilDir/dialog",
    "UtilDir/searchBlock",
	"UtilDir/combotree",
    "static/app/fwsjcj/taskmanage/fwsjcj",
	"static/app/fwsjcj/taskmanage/statisticalanalysisMap",
	"static/app/fwsjcj/taskmanage/detailedStatisticsMap",
    "static/app/fwsjcj/taskmanage/replayData",
    "static/app/fwsjcj/taskmanage/tmap",
	"static/app/fwsjcj/taskmanage/tmappublicmethod",
    "static/app/fwsjcj/taskmanage/mapTask",
	"static/app/fwsjcj/taskmanage/chinaRegion",
	"EasyUI","EasyUI-lang"
    ],function(Util,Tool,Dialog,SearchBlock,Combotree,fwsjcj,statisticalanalysisMap,detailedStatisticsMap){

    var sysPath =  getServer() + "/static/app/fwsjcj";

    var allotTaskFormHtml = sysPath + "/taskmanage/views/allottaskForm.html";
    var TaskFormHtml = sysPath + "/taskmanage/views/taskForm.html";
	var getDivisionController = function () {
		return getServer() + "/platform/org/divisions/";
	};
	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		createTaskGrid();
        //浏览器窗口大小变化后，表格宽度自适应
        $(window).resize(function(){
            createTaskGrid();
            //fwsjcj.fwsjcjInitAll();
            //replayInitAll();
        });
        debugger;
        fwsjcj.fwsjcjInitAll();
        //replayInitAll();
	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            createTaskGrid();
        });
        $("#btnReset").click(function () {
            $("#status").val("");
            $("#taskName").val("");
            $("#groupLeaderSearch").val("");
        });
	};
	$("#tasklistlab").on('shown.bs.tab', function (e) {
		createTaskGrid();
	});
    $("#taskMaplab").on('shown.bs.tab', function (e) {
        //fwsjcj.fwsjcjInitAll();
    });
    $("#replayMaplab").on('shown.bs.tab', function (e) {
        replayInitAll();
    });
	$("#statistical-analysisMaplab").on('shown.bs.tab', function (e) {
		statisticalanalysisMap.statisticalanalysisInitAll();
	});
	$("#detailedstatisticsMaplab").on('shown.bs.tab', function (e) {
		detailedStatisticsMap.detailedstatisticsInitAll();
	});
	var createTaskGrid = function() {
        $("#taskGrid").datagrid({
            url:getServer() + "/fw/task/page/0",
			method:"GET",
			nowrap: false,
            columns:[[
				{field:"ck",checkbox:true},
				{field:'taskNum',title:'任务编号',width:'15%',align:'center'},
                {field:'taskName',title:'任务名称',width:'19.75%',align:'center',
                    formatter:function(value,rowData,rowIndex){
                        return '<a href="#" onclick="_view(\'' + rowData.taskId + '\',\'' + rowData.groupId + '\',\'' +rowData.taskName + '\');"> '+rowData.taskName+' </a> '

                    }
                },
                {field:'taskType',title:'任务类别',width:'10%',align:'center',
                	formatter: function (value, rowData, rowIndex) {
                		if(value == '0'){
                			return '普查任务';
                		}else if(value == '1'){
                			return '详查任务';
                		}
                        
                    }
				},
                {field:'taskManager',title:'任务管理员',width:'10%',align:'center'},
                {field:'groupName',title:'承担小组',width:'15%',align:'center'},
                {field:'groupLeader',title:'组长',width:'10%',align:'center'},
                {field:'groupLeaderMobile',title:'手机号码',width:'10%',align:'center'},
                {field:'status',title:'任务状态',width:'10%',align:'center',
                	formatter: function (value, rowData, rowIndex) {
                		if(value == '0'){
                			return '未分配';
                		}else if(value == '1'){
                			return '进行中';
                		}else if(value == '2'){
                			return '已完成';
                		}                       
                    }
                },
//              {field:'operation',title:'操作',width:'14.8%',align:'center',
//              	formatter: function (value, rowData, rowIndex) {
//                      return '<a onclick="_complete(\'' + rowData.taskId+ '\')">完成</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onclick="_uncheck(\'' + rowData.taskId+ '\')">分配</a >';                        		
//                  }
//              }
            ]],
            toolbar: [{
                iconCls: 'fa fa-share-square-o',
                text:"分配",
                handler: function(){allotTask()}
            },{
                iconCls: 'fa fa-check-square-o',
                text:"完成",
                handler: function(){completeTask()}
            },{
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){deleteTask()}
            }],
            queryParams:{
                status: $("#status").val(),
                taskName: $("#taskName").val(),
                groupLeader: $("#groupLeaderSearch").val()
            },
            pagination: true,
            pageSize: 10
        });
    };



	var formValidator = function(){
		$("#zwForm").validate({
			rules : {
				zwName : {
					required :true,
					maxlength:100
				},
                zwCode : {
                    required :true,
                    maxlength:32,
                    remote: {
                        type: "GET",
                        url:  + "validateZwCode",
                        data: {  //要传递的参数
                            zwId: function () {
                                return $("#zwForm #zwId").val();
                            },
                            zwCode: function () {
                                return $("#zwForm #zwCode").val();
                            }
                        }
                    }
                },
				sort:{
					digits:true,
					min:1,
					max:255
				},
                description:{
					maxlength:256
				}
			},
			messages : {
                zwName : {
					required:"职务名称不允许为空!",
					maxlength:"职务名称长度不可以超过100"
				},
                zwCode : {
                    required:"职务编码不允许为空!",
                    maxlength:"职务编码长度不可以超过30",
                    remote: "职务编码重复，请重新输入"
                },
				sort:"顺序号必须是小于256的正整数",
                description:"描述长度不可以超过256"
			}
		});
	};
	var getTask = function(id){
		$.ajax({
			url: getServer() + "/fw/task/"+id,
			type: "get",
			success: function (data) {
				Tool.deserialize("taskForm", data);
			}
		});
	};

	var allotTask = function () {
		var rows = $("#taskGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0 || rows.length > 1) {
			Util.alert("请选择一行数据!");
			return;
		}else if(rows[0].status == '2'){
			Util.alert("任务状态为已完成的不能再分配小组!");
			return;
		}
		var slidebar = Util.slidebar({
			url: allotTaskFormHtml,
			width: "800px",
			cache: false,
			close : true,
			afterOpen: function () {
				createGroupGrid(rows);
			},
			afterLoad: function () {
				formValidator();
				initdivision();
				debugger;
				Tool.deserialize("allotTaskForm", rows[0]);
				$("#saveBtn").on("click", function () {
					if($("#allotTaskForm").valid()){
//						var data = Tool.serialize("allotTaskForm");
						var data = {
							taskId: $("#taskId").val(),
							taskName: $("#taskNameForm").val(),
							taskType: $("#taskType").val(),
							groupName: $("#taskGroup").val(),
							groupId: $("#groupId").val(),
							groupLeaderId: $("#groupLeaderId").val(),
							groupLeader: $("#groupLeader").val(),
							division: $("#divisionId").val(),
						}
						debugger;
						$.ajax({
							url: getServer() + "/fw/task/update",
                            contentType:"application/json",
							data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
                                createTaskGrid();
							}
						});
					}
				});
			}
		});
	};
	var completeTask = function () {
		var rows = $("#taskGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}else if(rows[0].status != '1'){
			Util.alert("只有任务状态为进行中的才能完成!");
			return;
		}else if(rows.length >= 1){
			for(let i = 0;i <rows.length;i++){
				if(rows[i].status != '1'){
					Util.alert("只有任务状态为进行中的才能完成!");
					return;
				}
			}
		}
		Util.confirm("是否要完成选中的任务?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.taskId + ",";
			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getServer() + "/fw/task/2/complete/"+ids,
				type: "post",
				success: function (data) {
					createTaskGrid();
				}
			});
		}, function() {
			return;
		});
	};
    var createGroupGrid = function (rows) {
        $("#groupGrid").datagrid({
            url: getServer() + "/fw/group/page?groupType=0",
            method: "get",
            nowrap: false,
            columns: [[                
                {
                    field: 'groupName',
                    title: '小组名称',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'groupLeader',
                    title: '小组组长',
                    width: '15%',
                    align: 'center'
                },
                {
                    field: 'groupMember',
                    title: '小组成员',
                    width: '27.8%',
                    align: 'center'
                },
                {
                    field: 'address',
                    title: '小组地区',
                    width: '25%',
                    align: 'center'
                },
                {field:'operation',title:'操作',width:'15%',align:'center',
                	formatter: function (value, rowData, rowIndex) {
                        return '<a onclick="_allot(\'' + rowData.groupName+ '\',\'' + rowData.id+ '\',\'' + rowData.groupLeaderId+ '\',\'' + rowData.groupLeader+ '\')">分配</a >';                        		
                    }
                }
            ]], 
//          data: [{
//                  groupName: "小组一",
//                  taskType: "普查任务",
//                  groupMembers: "张一",
//                  groupLeader: "李一",
//                  groupRegion: "北京市"
//              }],
            pagination: true,
            pageSize: 10
        });
    };
    window._allot = function (groupName,groupId,groupLeaderId,groupLeader) {
    	debugger;
    	$("#taskGroup").val(groupName);
    	$("#groupId").val(groupId);
    	$("#groupLeaderId").val(groupLeaderId);
    	$("#groupLeader").val(groupLeader);
    }
	window._view = function(taskId,groupId,taskName) {
		var slidebar = Util.slidebar({
			url: TaskFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {				
				getTask(taskId);
				//查看队员列表
		        $("#viewteamBtn").bind("click", function () {
		            var buttons = [];
		            buttons.push({
		                name: '确定',
		                callback: function () {
		                    //点击确定
		                    
		                    dialog.hide();
		                }
		            });
		
		            var dialog = Dialog({
		                id: "viewTeamDialog",
		                cache: false,
		                title: '队员情况', //dialog标题
		                width: "1000px",
		                height: "550px",
		                body: '<div id="TeamGrid"></div>',
		                buttons: buttons,
		                afterOpen: function () {
		                    $("#TeamGrid").datagrid({
		                        url: getServer() + "/fw/group/"+groupId,
		                        method: "GET",
		                        height:"515px",
		                        fitColumns: true,
		                        nowrap: false,
		                        autoRowHeight: false,
		                        singleSelect: true,
		                        columns: [[
		                            {field: 'relName', title: '姓名', width: '15%', align: 'center'},
									{field: 'idNumber', title: '身份证号', width: '25%', align: 'center'},
		                            {field: 'mobilePhone', title: '手机号', width: '20%', align: 'center'},
		                            {field: 'groupZW', title: '队内职务', width: '10%', align: 'center'},
		                            {field: 'formNum', title: '完成表单数量', width: '15%', align: 'center'},
		                            {field: 'operation', title: '操作', width: '17%', align: 'center',
			                            formatter: function (value, rowData, rowIndex) {
		                            	debugger;
					                        return '<a onclick="_viewTrajectory(\'' + rowData.userId+ '\',\'' + taskId+ '\',\'' +taskName+ '\',\'' +rowData.relName+ '\')">查看队员轨迹</a >';
					                    }
		                            },
		                        ]],
		
		                        pagination: false,
		                        pageSize: 10
		                    });
		                }
		            });
		            dialog.show();
		            window._viewTrajectory = function(userId,taskId,taskName,userName) {
				    	debugger;
				    	dialog.hide();
				    	slidebar.close();
				 		$('#myTab a[href="#replayMap"]').tab('show');
				 		//replayInitAll();
				 		startReplayData(userId,taskId,taskName,userName);
			    	}
		        });
				
			}
		});
	};
	var deleteTask = function() {
		var rows = $("#taskGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}else if(rows[0].status == '2'){
			Util.alert("任务状态为已完成的不能删除!");
			return;
		}else if(rows.length >= 1){
			for(let i = 0;i <rows.length;i++){
				if(rows[i].status == '2'){
					Util.alert("任务状态为已完成的不能删除!");
					return;

				}
			}
		}		
		Util.confirm("删除任务，该任务下关联的采集数据系统自动删除，是否删除任务?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += (row.taskId + "_"+ row.taskType) + ",";
			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getServer() + "/fw/task/"+ids,
				type: "post",
				success: function (data) {
					Util.alert(data.message);
					createTaskGrid();
				}
			});
		}, function() {
			return;
		});

	};
	var initdivision = function () {
		var combotree = Combotree({
			// combo组件相关配置
			combo: {
				//要渲染的input的id
				id: "division",
				//下拉框的类型：单选or多选
				multi: false,
				key: {
					idKey: "divisionId",
					textKey: "divisionName"
				},
				//          placeholder: "请选择……",
				event: {
					onShowPanel: function () {
						console.log("show");
					},
					onHidePanel: function () {
						console.log("hide");
					},
					onChange: function (n, o) {
						debugger;
						$("#divisionId").val(n[0].divisionId);
						$("#division").val(n[0].divisionName);
					}
				}
			},
			// ztree组件相关配置
			ztree: {
				data: {
					simpleData: {
						enable: true,
						idKey: "divisionId", // 主键属性名
						pIdKey: "parentId" // 父节点属性名
					},
					key: {
						name: "divisionName" // 显示名称属性名
					}
				},
				check: {
					chkboxType: {
						'Y': '',
						'N': ''
					}
				}
			},
			data: {
				url: getDivisionController() + 'initDivisionZtree',
				type: 'GET',
				success: function () {

				}
			},
			formatter: function (node) {
				node.open = false;
			},
			value: $("#divisionId").val(),
			search: {
				enable: true,
				fields: ["divisionName"]
			}
		});
	}
	return {
		init:init
	};
});

var replayMap;



